/*******************************************************************************
 *    版权信息   ： @copyright Copyright 2014-2021 chnenergy All Right Reserved
 *    作   者   ： hhz
 *    版   本   ： 1.1
 *    创建时间   ：2024/4/13
 *    最后修改日期   ： 2024/4/13
 *    最后修改人员   ： hhz
 ******************************************************************************/
package io.github.houhanzhi.hhregistry.model;

import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * instance meta model
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(of = {"scheme", "host", "port", "context"})
public class InstanceMeta {

    private String scheme;

    private String host;

    private Integer port;

    // 路径的上下文
    private String context;

    // online or offline
    // 通过该状态可进行蓝绿发布
    private boolean status;

    private Map<String, String> parameters = new HashMap<>();

    public InstanceMeta(String scheme, String host, Integer port, String context) {
        this.scheme = scheme;
        this.host = host;
        this.port = port;
        this.context = context;
    }

    public static InstanceMeta from(String url) {
        URI uri = URI.create(url);
        return new InstanceMeta(uri.getScheme(),
                uri.getHost(),
                uri.getPort(),
                uri.getPath().substring(1));
    }

    public String toPath() {
        return String.format("%s_%d", host, port);
    }

    public static InstanceMeta http(String host, Integer port) {
        return new InstanceMeta("http", host, port, "hhrpc");
    }

    public String toUrl() {
        return String.format("%s://%s:%d/%s", scheme, host, port, context);
    }


    public String toMetas() {
        return JSON.toJSONString(this.getParameters());
    }


    public InstanceMeta addParams(Map<String, String> metas) {
        this.getParameters().putAll(metas);
        return this;
    }
}
